#! /usr/bin/env python
# coding=utf-8

import json
import re
import pandas as pd

import argparse
import sys
from argparse import RawTextHelpFormatter




parser = argparse.ArgumentParser(
    description='''
    读取 miRNA的
    clus文件 
    side文件 （define_mature_side_using_reads.py获得的结果 可以手动修正一部分 ）
    RNAfold 文件 
    输出 用于上传数据库的miRNA表格

    输出必须加上 xlsx 不然会格式问题

    用法:
    make_product_miRNA.py -c result.clus -s side_prop -r miRNA_pre.fold -o miRNA.xlsx
    ''',formatter_class=RawTextHelpFormatter)



parser.add_argument('-c',
                help='必须给定，原始的 clus文件 ')
parser.add_argument('-s',
                help='必须给定，决定哪一边为 mature 的文件')
parser.add_argument('-r',
                help='必须给定，RNAfold文件 ')
parser.add_argument('-o',
                help='必须给定，输出的用于上传数据库的文件 ')



args = parser.parse_args()

if not args.c or not args.s or not args.r or not args.o:
    parser.print_help()
    sys.exit()

# 将miRNA的结果整理为 product文件

clus_file = args.c
RNAfold_file = args.r
side_file = args.s
outfile  =args.o



# 读取side 情况 对00 那种情况 作出警告

side_dic = {}
with open(side_file) as fila:
	for i in fila:
		k = i.strip().split('\t')
		if len(k)>=2:
			side_dic[k[0]] = k[1]
		#name = k[0]
		if len(k)>3 and k[2]=='0' and k[3]=='0': 
			print('%s reads map为0 需要检查' % k[0])

		#print(name)




miRNA_dic = {}

RNA_seq = re.compile('[A|T|C|G|U]+')
RNA_fold = re.compile(r'([.|(|)]+) \((.+)\)')


tmp_dic = {}

with open(RNAfold_file) as fila:

	for i in fila:
		i = i.strip()
		if len(i)>1:

			if i[0]=='>':

				
		
				tmp_dic['name'] = i[1:]
			else:
				#print(i.upper())
				k =  RNA_seq.match(i.upper())
				if k:
					tmp_dic['seq'] = i
				else:
				
					k = RNA_fold.findall(i.upper())
					if len(k)==1 and len(k[0]) ==2:

						tmp_dic['structure'] = k[0][0]
						tmp_dic['mfe'] = str(float(k[0][1]))

						#miRNA_dic[] = tmp_dic

						miRNA_dic[tmp_dic['name']] = tmp_dic
						tmp_dic = {}




outfile_write = pd.ExcelWriter(outfile)

df = pd.DataFrame(data=None,columns=['product_id','product_name','type','product_description','gene','product_structure','product_sequence','miRNA_mature','miRNA_star','mfe'])



with open(clus_file) as fila:
	for i in fila:
		k = i.strip().replace(',','\t').split('\t')

		gene = k[1]


		if gene in miRNA_dic and gene in side_dic:

			name = k[1]+'.seq'
			structure = json.dumps(miRNA_dic[gene])
			mfe = miRNA_dic[gene]['mfe']
			if side_dic[gene] =='5p':
				mature = k[3]
				star = k[4]
			else:
				mature = k[4]
				star = k[3]

			product_sequence = k[5]


			df = df.append({'product_id':'',
			'product_name':name,
			'type':'miRNA',
			'product_description':k[2],
			'gene':gene,
			
			'product_structure':structure,
			'product_sequence':product_sequence,
			'miRNA_mature':mature,
			'miRNA_star':star,
			'mfe':mfe,
			},ignore_index=True)



df.to_excel(outfile_write, index=False)

outfile_write.close()

		



						

						